package cn.netuo.bumbersoll;

import android.Manifest;
import android.app.AppOpsManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.rooten.help.permission.AppPermissionApply;
import com.tbruyelle.rxpermissions2.Permission;

import io.reactivex.functions.Consumer;
import lib.grasp.util.BarUtils;
import lib.grasp.util.L;
import lib.grasp.util.PermissionRxUtil;
import lib.grasp.widget.MessageBoxGrasp;

/**
 * Created by JS_grasp on 2019/3/18.
 * 1. 检查权限
 */
public class PermissionActivity extends AppCompatActivity implements Consumer<Permission> {

    String[] permissionStr = {};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BarUtils.setStatusBarVisibility(this, false);

        initPermission();
        if(Build.VERSION.SDK_INT <= 22){
            doScanToRegister();
        }
        else{
            if(doCheckPermission()) doScanToRegister();
            else requestPermission(permissionStr);
        }
    }

    private void initPermission() {
        permissionStr = new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
        };
    }

    private void requestPermission(String[] permissionStr){
        PermissionRxUtil.requireMultiDangerousPermissionForListener(this, permissionStr, this);
    }

    @Override
    public void accept(Permission permission) throws Exception {
        L.logOnly("---permission.name:" + permission.name + "-----" + permission.granted);

        if (permission.name.equalsIgnoreCase(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            if (permission.granted) {
                // 同意
            }else if (permission.shouldShowRequestPermissionRationale){
                // 禁止
            } else {
                // 禁止，且选择“以后不再询问”，以后申请权限，不会继续弹出提示
                MessageBoxGrasp.infoMsg(this, "缺少权限", "请手动授予本应用访问存储卡权限", false, v -> finish());
                return;
            }
        }

        if (permission.name.equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION)) {
            if (permission.granted) {
                // 同意
            }else if (permission.shouldShowRequestPermissionRationale){
                // 禁止
            } else {
                // 禁止，且选择“以后不再询问”，以后申请权限，不会继续弹出提示
                MessageBoxGrasp.infoMsg(this, "缺少权限", "请手动授予本应用卫星定位权限", false, v -> finish());
                return;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(!doCheckShouldRequestAgain()) {
            return;
        }

        if(doCheckPermission()) doScanToRegister();
        else requestPermission(permissionStr);
    }

    /** 检测还能不能弹出权限请求的窗口 */
    private boolean doCheckShouldRequestAgain() {
        for(String permission : permissionStr){
            boolean canRequestAgain = PermissionRxUtil.checkShouldShow(this, permission);
            if(!canRequestAgain){
                return false;
            }
        }
        return true;
    }

    /** 这里检测是否已经赋予相关权限  */
    private boolean doCheckPermission(){
        boolean isAllOk = true;
        for(String permission : permissionStr){
            boolean result = PermissionRxUtil.checkDangerousPermission(this, permission);
            isAllOk &= result;
        }
        return isAllOk;
    }

    /** 扫桌子上的二维码进行注册 */
    private void doScanToRegister(){
        if(!AppPermissionApply.hasSpecialPermission(this, AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW)){
            MessageBoxGrasp.infoMsg(this, "提示", "请允许[悬浮窗]权限", false, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AppPermissionApply.requestAlertWindowPermission(PermissionActivity.this);
                    finish();
                }
            });
            return;
        }

        Intent intent = new Intent(this, SelectBleActivity.class);
        startActivity(intent);
        finish();
    }
}
